package com.nlx.notes.support.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class SecurityBodyInterceptor implements HandlerInterceptor {
    private static final String[] ATTACK_KEYWORDS = {
            "sleep(", "union select", "jndi:", "ldap://", "rmi://",
            "${", "--", "/*", "*/", "or 1=1", "or true", "drop table"
    };

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String contentType = request.getContentType();
        if (contentType == null || !contentType.contains("application/json")) {
            return true; // 不处理非 JSON 请求
        }

        // 将 request 包装成可重复读的
        CachedBodyHttpServletRequest requestWrapper = new CachedBodyHttpServletRequest(request);

        String body = requestWrapper.getBody().toLowerCase();

        for (String keyword : ATTACK_KEYWORDS) {
            if (body.contains(keyword)) {
                response.setStatus(400);
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().write("{\"msg\": \"非法请求\"}");
                return false;
            }
        }

        // 替换原始 request
        request.setAttribute("cachedRequestBody", requestWrapper);
        return true;
    }
}
